package com.atguigu.gulimall.order.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
/**
 * 自定义 MQ 配置类
 * durable: 是否持久化, exclusive: 是否排他性, autoDelete: 是否自动删除, routingKey: 路由键
 * 如果配置发生改变，重新运行不会覆盖原来的，只能删了，重新生成
 */
@Configuration
public class MyMQConfig {
    /**
     * Topic 交换机 (要绑定两个队列，所以用 Topic 交换机)
     */
    @Bean
    public Exchange orderEventExchange() {
        return new TopicExchange("order-event-exchange", true, false);
    }

    /**
     * 死信队列
     */
    @Bean
    public Queue orderDeadQueue() {
        return new Queue("order.dead.queue", true, false, false);
    }

    /**
     * 延时队列
     */
    @Bean
    public Queue orderDelayQueue() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", "order-event-exchange");    //自定义死信放到哪个交换机
        arguments.put("x-dead-letter-routing-key", "order.dead.order");    //自定义死信路由键
        arguments.put("x-message-ttl", 60000);    //消息过期时间，毫秒，一分钟
        return new Queue("order.delay.queue", true, false, false, arguments);
    }

    /**
     * 绑定死信队列 到 交换机
     */
    @Bean
    public Binding orderDeadBinding() {
        return new Binding("order.dead.queue", Binding.DestinationType.QUEUE, "order-event-exchange",
                "order.dead.order", new HashMap<>());
    }

    /**
     * 绑定延时队列 到 交换机
     */
    @Bean
    public Binding orderDelayBinding() {
        return new Binding("order.delay.queue", Binding.DestinationType.QUEUE, "order-event-exchange",
                "order.delay.order", new HashMap<>());
    }

    /**
     * 绑定死信队列 到 交换机(订单释放和库存释放进行绑定)
     */
    @Bean
    public Binding orderDeadOtherBinding() {
        return new Binding("stock.dead.queue", Binding.DestinationType.QUEUE, "order-event-exchange",
                "order.dead.other", new HashMap<>());
    }

    /**
     * 秒杀队列
     */
    @Bean
    public Queue orderSeckillOrderQueue(){
        return new Queue("order.seckill.order.queue", true, false, false);
    }

    /**
     * 绑定秒杀队列 到 交换机
     */
    @Bean
    public Binding orderSeckillOrderQueueBinding(){
        return new Binding("order.seckill.order.queue", Binding.DestinationType.QUEUE, "order-event-exchange",
                "order.seckill.order", null);
    }
}

